package com.iotimc.attendancesystem.manage.person;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.iotimc.attendancesystem.Contract;
import com.iotimc.attendancesystem.R;
import com.iotimc.attendancesystem.dao.GreenDaoManager;
import com.iotimc.attendancesystem.dao.PersonEntityDao;
import com.iotimc.attendancesystem.datautil.ImageData;
import com.iotimc.attendancesystem.entity.PersonEntity;
import com.iotimc.attendancesystem.util.CustomDialog;
import com.iotimc.attendancesystem.util.ImageUtil;
import com.iotimc.attendancesystem.util.ShareUtil;
import com.iotimc.attendancesystem.util.TtsUtil;

import java.io.ByteArrayOutputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author david
 * @date 2017/11/28
 */

public class PersonDialog implements PersonContract.InsertOrUpdateView {
    private static final String TAG = "PersonDialog";
    PersonEntity personEntity;
    View view;
    @BindView(R.id.hint)
    TextView hint;
    @BindView(R.id.person_img)
    ImageView personImg;
    @BindView(R.id.admin)
    RadioButton admin;
    @BindView(R.id.ordinary)
    RadioButton ordinary;
    @BindView(R.id.code)
    EditText code;
    @BindView(R.id.name)
    EditText name;
    @BindView(R.id.male)
    RadioButton male;
    @BindView(R.id.female)
    RadioButton female;
    @BindView(R.id.position)
    EditText position;
    @BindView(R.id.card)
    EditText card;

    @OnClick({R.id.hint, R.id.background, R.id.img, R.id.info})
    void setHint() {
        if (fragment.getActivity().getCurrentFocus() != null && fragment.getActivity().getCurrentFocus().getWindowToken() != null) {
            InputMethodManager manager = (InputMethodManager) fragment.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (manager != null) {
                manager.hideSoftInputFromWindow(fragment.getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }


    AlertDialog dialog;
    boolean mHeadFlag;
    PersonEntityDao personEntityDao;
    Fragment fragment;
    private PersonContract.Presenter mPresenter;
    private CustomDialog customdialog;
    private CustomDialog.Builder mBuilder;

    public PersonDialog(@NonNull Fragment fragment, PersonContract.Presenter mPresenter) {
        this.fragment = fragment;
        this.mPresenter = mPresenter;
        this.mPresenter.setInsertOrUpdateView(this);
        personEntityDao = GreenDaoManager.getInstance().getSession().getPersonEntityDao();
        view = LayoutInflater.from(fragment.getContext()).inflate(R.layout.dialog_add_person, null);
        ButterKnife.bind(this, view);

       /* view = LayoutInflater.from(fragment.getActivity()).inflate(R.layout.dialog_add_person, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getActivity());
        builder.setTitle("添加人员");
        builder.setView(view);
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", null);
        dialog = builder.create();*/


        mBuilder = new CustomDialog.Builder(fragment.getContext())
                .setContentView(view)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PersonDialog.this.onClick();
                        //dismiss在insertOrUpdateSuccess()
                    }
                });

    }


    public void show() {
        resetView();
        if (customdialog == null) {
            customdialog = mBuilder.build();
        } else {
            customdialog.show();
        }

        mHeadFlag = false;
        mHeadByte = null;

        if (personEntity != null) {
            code.setText(personEntity.getCode());
            name.setText(personEntity.getName());
            position.setText(personEntity.getPosition());
            card.setText(personEntity.getCard());
            if (personEntity.getAdmin()) {
                admin.setChecked(true);
            } else {
                ordinary.setChecked(true);
            }
            if ("男".equals(personEntity.getSex())) {
                male.setChecked(true);
            } else {
                female.setChecked(true);
            }
            if (personEntity.getImage() != null && personEntity.getImage() != null) {
                /*PictureManager.getInstance()
                        .load(fragment.getActivity(),
                                personEntity.getImage(), personImg, false);*/
                personImg.setImageBitmap(ImageUtil.bytesToBitmap(personEntity.getImage()));
            } else {
                personImg.setImageDrawable(
                        fragment.getContext().getResources().getDrawable(R.drawable.ic_user_img));
            }

        } else {
            ordinary.setChecked(true);
            female.setChecked(true);
            code.setText("");
            card.setText("");
            name.setText("");
            position.setText("");
            mHeadByte = null;
            personImg.setImageDrawable(
                    fragment.getContext().getResources().getDrawable(R.drawable.ic_user_img));
        }
    }

    private void resetView() {
        this.hint.setText("");
        this.code.setFocusable(true);
        this.code.setFocusableInTouchMode(true);
        this.code.requestFocus();
        this.ordinary.setChecked(true);
        this.female.setChecked(true);
        this.code.setText("");
        this.card.setText("");
        this.name.setText("");
        this.position.setText("");
        this.code.setTextColor(fragment.getActivity().getResources().getColor(R.color.black));
        this.name.setTextColor(fragment.getActivity().getResources().getColor(R.color.black));
        this.card.setTextColor(fragment.getActivity().getResources().getColor(R.color.black));

        this.code.setHint("请输入编号");
        this.code.setHintTextColor(fragment.getActivity().getResources().getColor(R.color.gray));
        this.card.setHint("请刷卡录入");
        this.card.setHintTextColor(fragment.getActivity().getResources().getColor(R.color.gray));
        this.name.setHint("请输入姓名");
        this.name.setHintTextColor(fragment.getActivity().getResources().getColor(R.color.gray));
        this.position.setHintTextColor(fragment.getActivity().getResources().getColor(R.color.gray));
    }


    public void onClick() {
        String code = this.code.getText().toString().trim();
        String name = this.name.getText().toString().trim();
        String position = this.position.getText().toString().trim();
        String card = this.card.getText().toString();
        String sex = male.isChecked() ? "男" : "女";
        if (TextUtils.isEmpty(code)) {
            this.code.setHint("编号不能为空");
            this.code.setHintTextColor(fragment.getActivity().getResources().getColor(R.color.red));
            TtsUtil.ttsSpeek2("编号不能为空");
            return;
        }
        if (TextUtils.isEmpty(name)) {
            this.name.setHint("姓名不能为空");
            this.name.setHintTextColor(fragment.getActivity().getResources().getColor(R.color.red));
            TtsUtil.ttsSpeek2("姓名不能为空");
            return;
        }

        if (!mPresenter.checkCodeRepeat(personEntity != null ? personEntity.getCode() : "", code)) {
            this.code.setText("");
            this.code.setHint("编号已存在");
            this.code.setHintTextColor(fragment.getActivity().getResources().getColor(R.color.red));
            TtsUtil.ttsSpeek2("编号已存在");
            return;
        }
        if (!mPresenter.checkCardRepeat(personEntity != null ? personEntity.getCard() : "", card)) {
            this.card.setText("卡号已存在");
            this.card.setTextColor(fragment.getActivity().getResources().getColor(R.color.red));
            TtsUtil.ttsSpeek2("卡号已存在");
            return;
        }
        mPresenter.insertOrUpdate(personEntity, mHeadByte, admin.isChecked(), code, name, position, card, sex);
    }

    private byte[] mHeadByte;
    private int mHeadLength;

    public void setImageBitmap(int resultCode) {
        Log.i(TAG, "setImageBitmap: resultCode" + resultCode);
        if (resultCode == 0x80) {

            Bitmap image = ImageData.getColorImage();
            Rect rect = ImageData.getRect();
            Bitmap bitmapCrop = Bitmap.createBitmap(image, rect.left, rect.top,
                    rect.right - rect.left + 1, rect.bottom - rect.top + 1);
            personImg.setImageBitmap(bitmapCrop);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmapCrop.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            mHeadByte = stream.toByteArray();
            mHeadLength = mHeadByte.length;
            mHeadFlag = true;
        } else if (resultCode == 0x81) {
            mHeadByte = null;
            mHeadLength = 0;
            mHeadFlag = false;
        }

    }

    public boolean isShowing() {
        return customdialog.isShowing();//dialog.isShowing();
    }

    public void dismiss() {
        //dialog.dismiss();
        customdialog.dismiss();
        ((PersonManageFragment) fragment).notifyData();
    }

    public void setPersonEntity(PersonEntity personEntity) {
        this.personEntity = personEntity;
    }


    @OnClick(R.id.person_img)
    public void onViewClicked() {
        boolean b = ShareUtil.getBoolean(fragment.getActivity(), true, Contract.DEVICE_STATUS);
        if (b) {
            hint.setText("");
            ((PersonManageFragment) fragment).startBitmap();
        } else {
            TtsUtil.ttsSpeek2("设备打开失败，请重新打开设备！");
        }

    }

    public void setCard(String card) {
        this.card.setTextColor(fragment.getActivity().getResources().getColor(R.color.gray));
        this.card.setText(card);
    }

    @Override
    public void insertOrUpdateError(String message) {
        hint.setText(message);
    }

    @Override
    public void insertOrUpdateSuccess() {
        dismiss();
        this.personEntity = null;
    }
}
